<template>
	<b-submit-page bottomExtraClass="bg-color-1 bottom-shadow" bottomPdClass="p-2-2">
		<view
			class="p-3-1 border b-active-op20 rounded-m row-center mb-2-2 mx-1-3"
			hover-class="bg-primary-op10"
			hover-start-time="0"
			hover-stay-time="50"
			@click="toContact"
		>
			<view class="mr-3-1">
				<text class="iconfont icon-dingwei color-main text-xxl"></text>
			</view>
			<view v-if="loadingContact" class="flex-1">
				<c-skeleton active></c-skeleton>
			</view>
			<view v-else-if="contactData" class="flex-1">
				<view class="mb-1-3 row-center">
					<text class="color-main font-semibold mr-2 text-m">{{ contactData.consigneeName }}</text>
					<text class="color-main font-semibold text-m">{{ contactData.consigneeMobile }}</text>
					<view v-if="contactData.defaulted === 1" class="px-1 py-0-4 rounded-n bg-primary ml-2-2">
						<text class="text-xs color-white">默认地址</text>
					</view>
				</view>
				<view>
					<text class="color-secondary text-m">
						{{ [contactData.province, contactData.city, contactData.area, contactData.detailAddress].join(' ') }}
					</text>
				</view>
			</view>
			<view v-else class="flex-1">
				<text class="text-n color-secondary">暂无地址，请先设置</text>
			</view>
			<view class="pl-3-1">
				<text class="iconfont icon-you text-l color-secondary"></text>
			</view>
		</view>
		<view class="p-1-3 border b-active-op20 rounded-m mx-1-3 mb-2-2" v-if="orderData.length === 0">
			<c-empty></c-empty>
		</view>
		<view v-else class="border b-active-op20 rounded-m mx-1-3 mb-2-2 pt-2-2 px-2-2">
			<view class="rounded-xl flex flex-row items-stretch mb-2-2" v-for="el in orderData" :key="el.id">
				<view class="rounded-xl border b-active overflow-hidden mr-2">
					<c-img :src="el.thumbnail" :width="200" :height="200" />
				</view>
				<view class="flex-1 flex flex-column">
					<view class="row-center mb-2 break-all">
						<text class="color-main font-semibold text-m">{{ el.name }}</text>
					</view>
					<view>
						<text class="color-disable text-m block">{{ el.specifications }}</text>
					</view>
					<view class="flex-1" />
					<view class="row-center">
						<view class="flex-1">
							<text class="color-main font-semibold text-m mr-1-3">¥</text>
							<text class="color-main text-xl">{{ el.price }}</text>
						</view>
						<view>
							<text class="color-main text-m">x {{ actData ? '1' : el.quantity }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="border b-active-op20 rounded-m mx-1-3 mb-2-2">
			<c-list-item title="商品金额" hideArrow>
				<template #suffix>
					<text class="color-main text-m font-semibold"> ¥{{ intlNumberFormat(orderDataPrice) }} </text>
				</template>
			</c-list-item>
			<!--
			  style="text-decoration: line-through;"
			<c-list-item title="团购价格" hideArrow v-if="actData && actData.activityType === ActType.tuan">
				<template #suffix>
					<text class="color-main text-m font-semibold">¥{{ intlNumberFormat(actData.consumeValue) }}</text>
				</template>
			</c-list-item> -->
			<picker
				mode="selector"
				:range="getGoodWay"
				range-key="label"
				@change="getGoodWayChange"
				:value="curGoodWayIndex"
				:disabled="true"
			>
				<c-list-item title="提货方式" :tip="getGoodWay[curGoodWayIndex].label" hideArrow> </c-list-item>
			</picker>
			<c-list-item
				title="配送时间"
				:tip="deliveryTimeText || '请选择'"
				v-if="curGoodWayIndex === 1"
				@touch="showTimeSlot"
			>
			</c-list-item>
			<c-list-item title="运费" hideArrow v-if="curGoodWayIndex === 1">
				<template #suffix>
					<text class="color-main text-m font-semibold">¥{{ deliveryFee }}</text>
				</template>
			</c-list-item>
			<c-list-item title="储值卡" :tip="selectedStoredText || '请选择'" @touch="showStoredList"> </c-list-item>
			<!-- <c-list-item title="优惠券" tip="暂无可用" v-if="!actData"> </c-list-item>s -->
			<view class="text-right pb-2-2 pr-3-1">
				<text class="text-m color-main">合计: </text>
				<text class="text-l font-semibold color-error">¥{{ intlNumberFormat(sumPrice) }}</text>
			</view>
		</view>
		<select-time-slot :options="timeSlotOptions" title="期望配送时间" @select="handleTimeSlotSelect"></select-time-slot>
		<template #bottom>
			<view class="row-center">
				<view class="flex-1" />
				<view class="mr-3-1">
					<text class="text-l color-main">应付:</text>
					<text class="text-l font-semibold color-error">¥{{ intlNumberFormat(sumPrice) }}</text>
				</view>
				<view style="width: 200rpx">
					<c-button type="" @touch="toPay" text="去支付" :disabled="!contactData || orderData.length === 0" />
				</view>
			</view>
		</template>
		<sel-stored-list ref="setStoredListPopup" @select="handleStoredSel"></sel-stored-list>
	</b-submit-page>
</template>

<script>
import { ref, onMounted, computed } from 'vue';
import { listContactAddresses } from '@/base/api/contact.js';
import { intlNumberFormat } from '@/uni-sdk/utils/common.js';
import { ActType } from '@/base/common-data.js';
import authCache from '@/uni-sdk/utils/authCache';
import { createOrder, getPayInfo } from '@/base/api/member.js';
import { handlePay } from '@/base/common-business.js';

export default {
	onLoad() {
		const c = this.getOpenerEventChannel();
		c &&
			c.on('data', (data) => {
				if (data) {
					this.orderData = data.orderData;
					this.shoppingCartIds = data.shoppingCartIds;
					this.actData = data.actData;
					if (data.actData) {
						const actType = data.actData.activityType;
						if (actType === ActType.tuan) {
							uni.setNavigationBarTitle({
								title: '提交团购订单',
							});
						}
					}
				}
			});
	},
	setup() {
		//data
		const orderData = ref([]);
		const shoppingCartIds = ref([]);
		const actData = ref();
		//contact
		const contactData = ref();
		const loadingContact = ref(false);
		async function reloadContact(contactItem) {
			if (contactItem) {
				contactData.value = contactItem;
				return;
			}
			loadingContact.value = true;
			const data = await listContactAddresses(true);
			loadingContact.value = false;
			if (data) {
				const target = data.length === 1 ? data[0] : data.find((el) => el.defaulted === 1);
				contactData.value = target;
			}
		}
		onMounted(() => {
			reloadContact();
		});
		function toContact() {
			uni.navigateTo({
				url: '/pages/contact-manage/contact-manage',
				success(e) {
					e.eventChannel.emit('data', {
						reloadContact,
					});
				},
			});
		}
		const orderDataPrice = computed(() => {
			let re = 0;
			orderData.value.forEach((el) => {
				re += el.price * (el.quantity || 1);
			});
			return re;
		});
		//
		const sumPrice = computed(() => {
			let re = 0;
			if (actData.value) {
				re = actData.value.consumeValue;
			} else {
				orderData.value.forEach((el) => {
					re += el.price * (el.quantity || 1);
				});
			}
			if (curGoodWayIndex.value === 1) {
				re += deliveryFee.value;
			}
			re = re - selStoredBalance.value;
			return re < 0 ? 0 : re;
		});
		const deliveryFee = ref(10);
		async function toPay() {
			const community = authCache.getCommunity();
			if (community) {
				if (!contactData.value) {
					getApp().globalData.toast('请先选择地址');
					return;
				}
				if (orderData.value.length === 0) {
					getApp().globalData.toast('暂无商品数据');
					return;
				}
				if (!deliveryTimeText.value) {
					getApp().globalData.toast('请先选择配送时间');
					return;
				}
				const model = {
					communityId: community.id,
					name: contactData.value.consigneeName,
					phone: contactData.value.consigneeMobile,
					address: [
						contactData.value.province,
						contactData.value.city,
						contactData.value.area,
						contactData.value.detailAddress,
					].join(' '),
					payMethod: 0,
					deliveryTime: deliveryTimeText.value,
					detail: orderData.value.map((item) => ({
						productId: item.id,
						productName: item.name,
						quantity: item.quantity,
					})),
					storedValueIds: selStoredCards.value.map((el) => el.id),
				};
				const re = await createOrder(model);
				if (re) {
					const orderNo = re.orderNo;
					handlePay(orderNo, (re) => {
						if (re) {
							getApp().globalData.toast('支付成功', true);
						}
						uni.reLaunch({
							url: '/pages/home/me/me?orderNo=' + orderNo,
						});
					});
				}
			}
		}
		//
		const curGoodWayIndex = ref(1);
		const getGoodWay = ref([
			{ value: 0, label: '自提' },
			{ value: 1, label: '配送' },
		]);
		function getGoodWayChange(e) {
			curGoodWayIndex.value = +e.detail.value;
		}
		//快递上门时间
		const deliveryTimeText = ref('');
		const timeSlotOptions = ref();
		function showTimeSlot() {
			timeSlotOptions.value = {};
		}
		function handleTimeSlotSelect(e) {
			deliveryTimeText.value = e.day.dateText + ' ' + e.timeSlot.text;
		}

		const selectedStoredText = ref('');
		const setStoredListPopup = ref();
		function showStoredList() {
			setStoredListPopup.value.open();
		}
		const selStoredCards = ref([]);
		const selStoredBalance = ref(0);
		function handleStoredSel(sels) {
			let sum = 0;
			sels.forEach((el) => {
				sum += el.balance;
			});
			selStoredCards.value = sels;
			selStoredBalance.value = sum;
			selectedStoredText.value = sels.length > 0 ? `已选择${sels.length}张储值卡，抵扣${sum}元` : '';
		}
		return {
			sumPrice,
			toPay,
			loadingContact,
			toContact,
			contactData,
			intlNumberFormat,
			deliveryFee,
			getGoodWay,
			curGoodWayIndex,
			getGoodWayChange,
			timeSlotOptions,
			showTimeSlot,
			handleTimeSlotSelect,
			orderData,
			shoppingCartIds,
			actData,
			ActType,
			orderDataPrice,
			deliveryTimeText,
			selectedStoredText,
			showStoredList,
			setStoredListPopup,
			handleStoredSel,
		};
	},
};
</script>

<style></style>
